<?php
/**
 * Created by PhpStorm.
 * User: majiawen
 * Date: 2018/2/8
 * Time: 15:01
 */

namespace app\admin\controller\v1;


use app\admin\controller\Fun;
// use app\admin\service\BusinessUpdateService;
use app\api\service\RegionService;
use app\common\Model\Freight as FreightModel;
use think\Db;

/**
 * @title 后台-价格管理-价格规则设置-V1
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class Freight extends Base
{

    /**
     * @title 开通城市运费列表
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Freight desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:freightList desc:开通城市管理列表
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:page type:string require:1 default: other:2 desc:页码
     * @param name:page_size type:string require:1 default: other: desc:每页个数
     * @param name:search type:string require:1 default: other:北京 desc:查询数据
     * @param name:sort_field type:string require:1 default: other: desc:排序字段
     * @param name:sort_type type:string require:1 default: other: desc:0正序,1倒序
     *
     * @return data:[]
     */
    public function freightList()
    {
        $where['is_del'] = 0;
        if (isset($this->param['search']) && $this->param['search'] != '') {
            $search = $this->param['search'];

            $wherefind = [
                'name' => ['like', '%' . $search . '%']
            ];
            $region_info = Db::name('region')->where($wherefind)->column('region_id');
            $where = [
                'province_region_id|city_region_id|area_region_id' => ['in', $region_info]
            ];
        }
        $used_sort_field = ['id', 'province_name', 'city_name', 'area_name'];
        if (isset($this->param['sort_field']) && $this->param['sort_field'] != '' && in_array($this->param['sort_field'], $used_sort_field) && isset($this->param['sort_type'])) {
            $order = [
                $this->param['sort_field'] => $this->sort_type[intval($this->param['sort_type'])]
            ];
        } else {
            $order = ['create_time' => $this->sort_type[1]];
        }
        $where['is_del'] = 0;//0是未删除
        $list = Db::name('freight f')
            ->join([
                ['region a', 'f.province_region_id=a.region_id', 'LEFT'],
                ['region b', 'f.city_region_id=b.region_id', 'LEFT'],
//                ['region c','f.area_region_id=c.region_id','LEFT'] ,
            ])
            ->where($where)
            ->order($order)
            ->field('
            f.f_id id,
            f.price,
            f.create_time,
            a.region_id province_id,
            a.name province_name,
            b.region_id city_id,
            b.name city_name
            ')
            ->paginate($this->page_size, false, ['page' => $this->param['page']]);
        if ($list) {
            $data = [];
            foreach ($list->items() as $k => $v) {
                $v['price'] = $v['price'] / 100;
                $data[] = $v;
            }
            return Fun::success(['list' => $data, 'total_num' => $list->total()]);
        } else {
            return Fun::error('333332');//TODO 无数据，定义错误类型
        }
    }

    /**
     * @title 省列表
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Freight desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:getAllProvince desc:
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @return data:[]
     */
    public function getAllProvince()
    {
        $where = ['parent_id' => 0];
        $list = Db::name('region')
            ->where($where)
            ->order('region_id')
            ->field('region_id,name')
            ->select();
//        $arr = [
//            'region_id' => 0 ,
//            'name' => '全国',
//        ];
//        array_unshift($list,$arr);
        if ($list) {
            return Fun::success($list);
        } else {
            return Fun::error('333332');//TODO 无数据，定义错误类型
        }
    }

    /**
     * @title 市区列表
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Freight desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:getCityAreaById desc:市区列表
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:id type:string require:1 default: other:110000 desc:所选省市的ID
     *
     * @return data:[]
     */
    public function getCityAreaById()
    {
        if (!isset($this->param['id'])) {
            return Fun::error('');//TODO 无数据，定义错误类型
        }
        $id = intval($this->param['id']);
        if ($id == 0) {
            return Fun::success([
                [
                    'region_id' => 0,
                    'name' => '全国',
                ]
            ]);
        }
        $list = Db::name('region')
            ->where(['parent_id' => $id])
            ->field('region_id,name')
            ->select();
        $region = Db::name('region')
            ->where(['region_id' => $id])
            ->field('region_id,name')
            ->find();
        array_unshift($list, $region);
        if ($list) {
            return Fun::success($list);
        } else {
            return Fun::error('333332');//TODO 无数据，定义错误类型
        }
    }

    /**
     * @title 添加新的地区运费
     * @description
     * @author jikesen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Freight desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:addFreight desc:添加修改新的地区运费
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:p_id type:string require:1 default: other:110000 desc:省id
     * @param name:c_id type:string require:1 default: other:110100 desc:市id
     * @param name:price type:string require:1 default: other:1.35 desc:运费价格
     *
     * @return data:[]
     */
    public function addFreight()
    {
        if (empty($this->param['p_id']) || empty($this->param['c_id']) || empty($this->param['price'])) {
            return Fun::error('801007');
        }

        $model = model('app\common\Model\Freight');

        //判断是否已经添加
        $_is_add_date = $model->where('province_region_id', $this->param['p_id'])->where('city_region_id', $this->param['c_id'])->find();

        if ($_is_add_date != null) {

            $data = $_is_add_date->getData();

            if (!empty($data)) {
                return Fun::error('400004');
            }
        }

        //新增数据
        $model->province_region_id = $this->param['p_id'];
        $model->city_region_id = $this->param['c_id'];
        $model->area_region_id = '';
        $model->price = $this->param['price'] * config('convert_unit');
        $model->is_del = FreightModel::IS_DEL_FALSE;

        if ($model->save()) {
            //缓存
            if (RegionService::instance()->regionList()) {
                return Fun::success('添加成功缓存成功');
            }
            return Fun::success('添加成功未缓存');
        } else {
            return Fun::error('333332');
        }
    }

    /**
     * @title 更新地区运费
     * @description
     * @author jikesen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Freight desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:addFreight desc:添加修改新的地区运费
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:id type:string require:1 default: other:110000 desc:id
     * @param name:p_id type:string require:1 default: other:110000 desc:省id
     * @param name:c_id type:string require:1 default: other:110100 desc:市id
     * @param name:price type:string require:1 default: other:1.35 desc:运费价格
     *
     * @return data:[]
     */
    public function updateFreight()
    {
        if (empty($this->param['id']) || empty($this->param['p_id']) || empty($this->param['c_id']) || empty($this->param['price'])) {
            return Fun::error('801007');
        }

        $model = model('app\common\Model\Freight');

        //判断是否已经添加
        $_date = $model->where('f_id', $this->param['id'])->find();

        if ($_date != null) {
            if (empty($_date->getData())) {
                return Fun::error('44444', '查询数据不存在');
            }
        }

        //更新
        $model->where('f_id', $this->param['id']);
        $model->province_region_id = $this->param['p_id'];
        $model->city_region_id = $this->param['c_id'];
        $model->area_region_id = '';
        $model->price = $this->param['price'] * config('convert_unit');

        if ($model->isUpdate(true)->save()) {

            //缓存
            if (RegionService::instance()->regionList()) {
                return Fun::success('更新成功缓存成功');
            }
            return Fun::success('更新成功未缓存');
        } else {
            return Fun::error('333332');
        }
    }

    /**
     * @title 删除地区运费
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:Freight desc:接口组(全局)
     *
     * @param name:command type:string require:1 default: other:delFreightById desc:捎货人种类排序移动
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:id type:string require:1 default: other:110000 desc:运费
     *
     * @return data:[]
     */
    public function delFreightById()
    {
        if (!isset($this->param['id'])) {
            return Fun::error('');//TODO 无数据，定义错误类型
        }
        $freight = new \app\common\Model\Freight();
        $where['f_id'] = intval($this->param['id']);
        $is_del = $freight::IS_DEL_TRUE;
        $res = $freight
            ->where($where)
            ->find();;
        if (!$res) {
            return Fun::error('333333');//TODO 无数据，定义错误类型
        } else {
            $freight = $res;
        }
        $freight->is_del = $is_del;

        //根据acc_id查询uid
        $user = DB::name('admin_user')->where(['acc_id' => $this->param['acc_id']])->field('uid')->find();
        $uid = $user['uid'];
        $freight->save();
        if ($freight->f_id) {
            //缓存
            if (RegionService::instance()->regionList()) {
                return Fun::success('删除成功缓存成功');
            }
            return Fun::success('删除成功未缓存');
        } else {
            return Fun::error('333332');
        }
    }
}